package com.chen.servicemap.remote;

import com.alibaba.fastjson2.JSONObject;
import com.chen.internalcommon.constant.MapConfigConstants;
import com.chen.internalcommon.dto.ResponseResult;
import com.chen.internalcommon.request.PointDTO;
import com.chen.internalcommon.request.PointRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

/**
 * @author chenLiuPing
 **/
@Service
@Slf4j
public class PointClient {
    @Value("${map.key}")
    private String key;

    @Value(("${map.sid}"))
    private String sid;

    @Autowired
    private RestTemplate restTemplate;

    public ResponseResult upload(PointRequest pointRequest) {
        // 拼接url
        StringBuilder url = new StringBuilder(MapConfigConstants.POINT_UPLOAD);
        url.append("?key=").append(key);
        url.append("&sid=").append(sid);
        url.append("&tid=").append(pointRequest.getTid());
        url.append("&trid=").append(pointRequest.getTrid());
        url.append("&points=");
        PointDTO[] points = pointRequest.getPoints();
        // 使用url编码来拼接
        url.append("%5B");  // [
        for (PointDTO point : points) {
            url.append("%7B"); // {
            url.append("%22location%22%3A"); // location":
            url.append("%22").append(point.getLocation()).append("%22").append("%2C");
            url.append("%22locatetime%22%3A");
            url.append("%22").append(point.getLocatetime()).append("%22");
            url.append("%7D");
        }
        url.append("%5D");
        log.info("url:{}", url);
        ResponseEntity<String> forEntity = restTemplate.postForEntity(URI.create(url.toString()), null, String.class);
        String body = forEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        String errmsg = jsonObject.getString("errmsg");
        if ("OK".equals(errmsg)) {
            log.info("创建轨迹成功");
            return ResponseResult.success();
        }
        String errdetail = jsonObject.getString("errdetail");
        log.info("创建轨迹失败：{}", errdetail);
        return ResponseResult.fail(errdetail);
    }
}
